# Oracle客户端环境快速配置脚本
# 用于DMZ服务器上的Oracle客户端环境变量配置
# 需要以管理员身份运行

param(
    [Parameter(Mandatory=$false)]
    [ValidateSet("32", "64", "auto")]
    [string]$Architecture = "auto",
    
    [Parameter(Mandatory=$false)]
    [switch]$Force
)

# 检查管理员权限
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Host "错误: 此脚本需要管理员权限运行" -ForegroundColor Red
    Write-Host "请以管理员身份重新运行PowerShell" -ForegroundColor Yellow
    exit 1
}

Write-Host "=== Oracle客户端环境配置脚本 ===" -ForegroundColor Green
Write-Host ""

# Oracle客户端路径
$client32Path = "D:\app\Administrator\product\11.2.0\client_1"
$client64Path = "D:\app\Administrator\product\11.2.0\client_2"

# 检查客户端安装
Write-Host "1. 检查Oracle客户端安装..." -ForegroundColor Yellow
$client32Exists = Test-Path $client32Path
$client64Exists = Test-Path $client64Path

Write-Host "   32位客户端 ($client32Path): $(if($client32Exists){'存在'}else{'不存在'})" -ForegroundColor $(if($client32Exists){'Green'}else{'Red'})
Write-Host "   64位客户端 ($client64Path): $(if($client64Exists){'存在'}else{'Red'})" -ForegroundColor $(if($client64Exists){'Green'}else{'Red'})

if (-not $client32Exists -and -not $client64Exists) {
    Write-Host "错误: 未找到任何Oracle客户端安装" -ForegroundColor Red
    exit 1
}

Write-Host ""

# 确定使用的架构
Write-Host "2. 确定目标架构..." -ForegroundColor Yellow

$targetArchitecture = $Architecture
if ($Architecture -eq "auto") {
    # 检查操作系统架构
    if ([Environment]::Is64BitOperatingSystem) {
        if ($client64Exists) {
            $targetArchitecture = "64"
            Write-Host "   自动选择: 64位 (推荐用于64位操作系统)" -ForegroundColor Green
        } elseif ($client32Exists) {
            $targetArchitecture = "32"
            Write-Host "   自动选择: 32位 (64位客户端不可用)" -ForegroundColor Yellow
        }
    } else {
        $targetArchitecture = "32"
        Write-Host "   自动选择: 32位 (32位操作系统)" -ForegroundColor Green
    }
} else {
    Write-Host "   手动指定: $targetArchitecture 位" -ForegroundColor Cyan
}

# 设置目标路径
$targetClientPath = if ($targetArchitecture -eq "64") { $client64Path } else { $client32Path }
$targetBinPath = Join-Path $targetClientPath "bin"
$targetTnsAdmin = Join-Path $targetClientPath "network\admin"

# 验证目标路径
if (-not (Test-Path $targetClientPath)) {
    Write-Host "错误: 目标Oracle客户端路径不存在: $targetClientPath" -ForegroundColor Red
    exit 1
}

if (-not (Test-Path $targetBinPath)) {
    Write-Host "错误: Oracle客户端bin目录不存在: $targetBinPath" -ForegroundColor Red
    exit 1
}

Write-Host "   目标客户端路径: $targetClientPath" -ForegroundColor White
Write-Host ""

# 检查当前环境变量
Write-Host "3. 检查当前环境变量..." -ForegroundColor Yellow
$currentOracleHome = [Environment]::GetEnvironmentVariable("ORACLE_HOME", "Machine")
$currentTnsAdmin = [Environment]::GetEnvironmentVariable("TNS_ADMIN", "Machine")
$currentPath = [Environment]::GetEnvironmentVariable("PATH", "Machine")

Write-Host "   当前ORACLE_HOME: $(if($currentOracleHome){$currentOracleHome}else{'未设置'})" -ForegroundColor $(if($currentOracleHome){'Yellow'}else{'Gray'})
Write-Host "   当前TNS_ADMIN: $(if($currentTnsAdmin){$currentTnsAdmin}else{'未设置'})" -ForegroundColor $(if($currentTnsAdmin){'Yellow'}else{'Gray'})

# 检查PATH中的Oracle路径
$oraclePathsInPath = $currentPath -split ';' | Where-Object { $_ -like '*oracle*' -or $_ -like '*client*' }
if ($oraclePathsInPath) {
    Write-Host "   PATH中的Oracle路径:" -ForegroundColor Yellow
    foreach ($path in $oraclePathsInPath) {
        Write-Host "     - $path" -ForegroundColor Gray
    }
} else {
    Write-Host "   PATH中无Oracle路径" -ForegroundColor Gray
}

Write-Host ""

# 询问是否继续
if (-not $Force) {
    $continue = Read-Host "是否继续配置Oracle环境变量? (y/N)"
    if ($continue -ne 'y' -and $continue -ne 'Y') {
        Write-Host "操作已取消" -ForegroundColor Yellow
        exit 0
    }
}

Write-Host ""
Write-Host "4. 配置环境变量..." -ForegroundColor Yellow

try {
    # 设置ORACLE_HOME
    Write-Host "   设置ORACLE_HOME = $targetClientPath" -ForegroundColor Green
    [Environment]::SetEnvironmentVariable("ORACLE_HOME", $targetClientPath, "Machine")
    
    # 设置TNS_ADMIN
    Write-Host "   设置TNS_ADMIN = $targetTnsAdmin" -ForegroundColor Green
    [Environment]::SetEnvironmentVariable("TNS_ADMIN", $targetTnsAdmin, "Machine")
    
    # 更新PATH
    Write-Host "   更新PATH环境变量..." -ForegroundColor Green
    
    # 移除现有的Oracle路径
    $pathParts = $currentPath -split ';' | Where-Object { 
        $_ -and 
        $_ -notlike '*oracle*' -and 
        $_ -notlike '*client*' -and
        $_ -ne $targetBinPath
    }
    
    # 添加新的Oracle路径到最前面
    $newPath = @($targetBinPath) + $pathParts -join ';'
    [Environment]::SetEnvironmentVariable("PATH", $newPath, "Machine")
    
    Write-Host "   ✓ 环境变量配置完成" -ForegroundColor Green
    
} catch {
    Write-Host "错误: 配置环境变量失败: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

Write-Host ""
Write-Host "5. 验证配置..." -ForegroundColor Yellow

# 重新读取环境变量
$newOracleHome = [Environment]::GetEnvironmentVariable("ORACLE_HOME", "Machine")
$newTnsAdmin = [Environment]::GetEnvironmentVariable("TNS_ADMIN", "Machine")
$newPath = [Environment]::GetEnvironmentVariable("PATH", "Machine")

Write-Host "   ORACLE_HOME: $newOracleHome" -ForegroundColor $(if($newOracleHome -eq $targetClientPath){'Green'}else{'Red'})
Write-Host "   TNS_ADMIN: $newTnsAdmin" -ForegroundColor $(if($newTnsAdmin -eq $targetTnsAdmin){'Green'}else{'Red'})

# 检查PATH中是否包含目标路径
$pathContainsTarget = $newPath -split ';' | Where-Object { $_ -eq $targetBinPath }
Write-Host "   PATH包含Oracle bin路径: $(if($pathContainsTarget){'是'}else{'否'})" -ForegroundColor $(if($pathContainsTarget){'Green'}else{'Red'})

Write-Host ""
Write-Host "6. 测试Oracle客户端..." -ForegroundColor Yellow

# 测试sqlplus
$sqlplusPath = Join-Path $targetBinPath "sqlplus.exe"
if (Test-Path $sqlplusPath) {
    try {
        Write-Host "   测试sqlplus版本..." -ForegroundColor Cyan
        $env:ORACLE_HOME = $targetClientPath
        $env:TNS_ADMIN = $targetTnsAdmin
        $versionOutput = & $sqlplusPath -version 2>&1
        Write-Host "   $versionOutput" -ForegroundColor White
    } catch {
        Write-Host "   sqlplus测试失败: $($_.Exception.Message)" -ForegroundColor Red
    }
} else {
    Write-Host "   警告: sqlplus.exe未找到" -ForegroundColor Yellow
}

# 测试tnsping
$tnspingPath = Join-Path $targetBinPath "tnsping.exe"
if (Test-Path $tnspingPath) {
    try {
        Write-Host "   测试TNS连接..." -ForegroundColor Cyan
        $env:ORACLE_HOME = $targetClientPath
        $env:TNS_ADMIN = $targetTnsAdmin
        $tnspingResult = & $tnspingPath "10.3.255.250:15521/HISDB" 2>&1
        if ($tnspingResult -like "*OK*") {
            Write-Host "   ✓ TNS连接测试成功" -ForegroundColor Green
        } else {
            Write-Host "   TNS连接测试结果:" -ForegroundColor Yellow
            Write-Host "   $tnspingResult" -ForegroundColor White
        }
    } catch {
        Write-Host "   tnsping测试失败: $($_.Exception.Message)" -ForegroundColor Red
    }
} else {
    Write-Host "   警告: tnsping.exe未找到" -ForegroundColor Yellow
}

Write-Host ""
Write-Host "=== 配置完成 ===" -ForegroundColor Green
Write-Host ""
Write-Host "重要提示:" -ForegroundColor Cyan
Write-Host "1. 环境变量已更新，但当前PowerShell会话可能需要重启才能生效" -ForegroundColor Yellow
Write-Host "2. 请重启.NET应用程序以使用新的Oracle客户端配置" -ForegroundColor Yellow
Write-Host "3. 如果仍有问题，请运行 check-oracle-client-environment.ps1 进行详细诊断" -ForegroundColor Yellow
Write-Host ""
Write-Host "下一步操作:" -ForegroundColor Cyan
Write-Host "1. 重启PowerShell会话" -ForegroundColor White
Write-Host "2. 重新启动.NET服务" -ForegroundColor White
Write-Host "3. 运行连接测试" -ForegroundColor White